package com.letao.rest.service.impl;

import com.letao.common.pojo.CategaryNode;
import com.letao.common.pojo.CategaryResult;
import com.letao.mapper.TbItemCatMapper;
import com.letao.pojo.TbItemCat;
import com.letao.pojo.TbItemCatExample;
import com.letao.rest.service.ItemCatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/1/12.
 */
@Service
public class ItemCatServiceImpl implements ItemCatService{

    @Autowired
    TbItemCatMapper tbItemCatMapper;

    public CategaryResult getCatList(){
        CategaryResult categaryResult = new CategaryResult();
        List<CategaryNode> data = getCatByParentID(0l);
        categaryResult.setData(data);
        return categaryResult;
    }

    /**
     * 装入查得的子类
     * @param parentID
     * @return
     */
    private List getCatByParentID(Long parentID){
        TbItemCatExample example = new TbItemCatExample();
        example.createCriteria().andParentIdEqualTo(parentID);
        List<TbItemCat> itemCats = tbItemCatMapper.selectByExample(example);
        List items = new ArrayList();
        for (TbItemCat cat: itemCats) {
            if(cat.getIsParent()){
                CategaryNode node = new CategaryNode();
                node.setUrl("/products/"+ cat.getId() +".html");
                if(0l == cat.getParentId()){
                    node.setName("<a href='/products/"+ cat.getId() +".html'>"+cat.getName()+"</a>");
                }else{
                    node.setName(cat.getName());
                }
                List list = getCatByParentID(cat.getId());
                node.setItems(list);
                items.add(node);
            }else{
                items.add(cat.getId() + "|"+ cat.getName());
            }
        }
        return items;
    }

}
